package com.loongtech.bi.action.system;

import com.loongtech.bi.entity.system.EntityAdvConfig;
import com.loongtech.bi.manager.system.AdvConfigManager;
import com.loongtech.bi.support.ExcelUtils;
import com.loongtech.core.util.Utils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName: AdvConfigAction
 *
 * @author liuchen
 * @Description: 广告配置
 * @date 2016-11-14 下午5:04:18
 */
@Controller("advConfigAction")
@Scope("view")
public class AdvConfigAction {

    private final String tmpuploaddir = "/usr/local/tomcat/upload/";

    @Autowired
    private AdvConfigManager advConfigManager;

    private int uploadparamtype;
    private static File file;
    private Map<String, Integer> queryGameParamTypeItmes;

    private List<EntityAdvConfig> list;
    private EntityAdvConfig entity;

    @Autowired
    public void init() {
        initData();
    }

    private void initData() {
        entity = new EntityAdvConfig(RandomStringUtils.randomAlphanumeric(6));
        list = AdvConfigManager.ADV_CONFIG_LIST;
        advConfigManager.init();
        search();
    }

    public void search() {
        List<Object> cons = new ArrayList<Object>();
        StringBuffer hql = new StringBuffer(" from EntityAdvConfig l where 1=1 ");
        if (!Utils.isEmptyStr(entity.getId())) {
            hql.append(" and l.id = ? ");
            cons.add(entity.getId());
        }
        if (!Utils.isEmptyStr(entity.getAffiliation())) {
            hql.append(" and l.affiliation like ? ");
            cons.add("%" + entity.getAffiliation() + "%");
        }
        if (!Utils.isEmptyStr(entity.getActName())) {
            hql.append(" and l.actName like ? ");
            cons.add("%" + entity.getActName() + "%");
        }
        if (!Utils.isEmptyStr(entity.getChannelName())) {
            hql.append(" and l.channelName like ? ");
            cons.add("%" + entity.getChannelName() + "%");
        }
        if (!Utils.isEmptyStr(entity.getAgent())) {
            hql.append(" and l.agent like ? ");
            cons.add("%" + entity.getAgent() + "%");
        }
        if (!Utils.isEmptyStr(entity.getPlatform())) {
            hql.append(" and l.platform like ? ");
            cons.add("%" + entity.getPlatform() + "%");
        }
        if (!Utils.isEmptyStr(entity.getPaytype())) {
            hql.append(" and l.paytype like ? ");
            cons.add("%" + entity.getPaytype() + "%");
        }
        if (!Utils.isEmptyStr(entity.getAdvPosition())) {
            hql.append(" and l.advPosition like ? ");
            cons.add("%" + entity.getAdvPosition() + "%");
        }
        list = advConfigManager.findByQuery(hql.toString(), cons.toArray());
    }

    public void add() {
        FacesContext context = FacesContext.getCurrentInstance();
        if (validate(context, entity, true, list)) {
            advConfigManager.persist(entity);
            context.addMessage(null, new FacesMessage("添加成功！"));
            initData();
            advConfigManager.init();
        }
    }

    public void modify(EntityAdvConfig e) {
        FacesContext context = FacesContext.getCurrentInstance();
        if (validate(context, e, false, list)) {
            advConfigManager.merge(e);
            context.addMessage(null, new FacesMessage("修改成功！"));
            initData();
            advConfigManager.init();
        }
    }

    public void delete(String id) {
        FacesContext context = FacesContext.getCurrentInstance();
        if (!Utils.isEmptyStr(id)) {
            advConfigManager.removeById(id);
        }
        context.addMessage(null, new FacesMessage("删除成功！"));
        initData();
        advConfigManager.init();
    }

    public void upload(FileUploadEvent event) throws IOException {
        System.out.println("upload file: ");
        UploadedFile ufile = event.getFile();
        if (ufile != null) {
            InputStream inputStream = ufile.getInputstream();

            File tmpdir = new File(tmpuploaddir);
            if (!tmpdir.exists()) {
                tmpdir.mkdir();
            }
            file = new File(tmpuploaddir + ufile.getFileName() + System.currentTimeMillis());
            file.createNewFile();

            OutputStream outputStream = new FileOutputStream(file);
            byte[] b = new byte[1024];
            while ((inputStream.read(b)) != -1) {
                outputStream.write(b);
            }
            inputStream.close();
            outputStream.close();
        }
        System.out.println("上传了文件：" + file == null ? file : file.getAbsolutePath());
    }

    public List<EntityAdvConfig> parseUploadedExcel(File file) throws Exception {
        FacesContext context = FacesContext.getCurrentInstance();
        List<EntityAdvConfig> result = new ArrayList<>();
        InputStream input = new FileInputStream(file);
        Workbook wb = WorkbookFactory.create(input);
        Sheet tempSheet = wb.getSheetAt(0);
        if (tempSheet == null) {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "数据错误！"));
            IOUtils.closeQuietly(input);

            return result;
        }
        int rowNum = tempSheet.getLastRowNum();// 获得总行数
        for (int i = 0; i <= rowNum; i++) {
            Row row = tempSheet.getRow(i);
            if (row == null) {
                continue;
            }
            String id = "".equals(ExcelUtils.getCellValue(row.getCell(0))) ? RandomStringUtils.randomAlphanumeric(6) : ExcelUtils.getCellValue(row.getCell(0));
            String affiliation = ExcelUtils.getCellValue(row.getCell(1));
            String actName = ExcelUtils.getCellValue(row.getCell(2));
            String channelName = ExcelUtils.getCellValue(row.getCell(3));
            String agent = ExcelUtils.getCellValue(row.getCell(4));
            String platform = ExcelUtils.getCellValue(row.getCell(5));
            String paytype = ExcelUtils.getCellValue(row.getCell(6));
            String advPosition = ExcelUtils.getCellValue(row.getCell(7));

            if ("".equals(affiliation) || "".equals(actName) || "".equals(channelName) || "".equals(agent) || "".equals(platform) || "".equals(paytype)
                    || "".equals(advPosition)) {
                continue;
            }

            EntityAdvConfig e = new EntityAdvConfig();
            e.setId(id);
            e.setAffiliation(affiliation);
            e.setActName(actName);
            e.setChannelName(channelName);
            e.setAgent(agent);
            e.setPlatform(platform);
            e.setPaytype(paytype);
            e.setAdvPosition(advPosition);
            result.add(e);
        }
        IOUtils.closeQuietly(input);
        return result;
    }

    public void parseExcel() {
        FacesContext context = FacesContext.getCurrentInstance();
        StringBuilder errorid = new StringBuilder();
        if (file != null && file.exists()) {
            try {
                List<EntityAdvConfig> tmp = parseUploadedExcel(file);
                if (tmp != null && tmp.size() > 0) {
                    for (EntityAdvConfig e : tmp) {
                        if (AdvConfigManager.ID_LIST.contains(e.getId().trim())) {
                            errorid.append(e.getId() + ",");
                            continue;
                        }

                        AdvConfigManager.ID_LIST.add(e.getId());
                        advConfigManager.persist(e);
                    }
                    initData();
                    if (errorid.length() > 0) {
                        context.addMessage(null, new FacesMessage("解析成功！包含重复短链 ： " + errorid.substring(0, errorid.length() - 1)));
                    } else {
                        context.addMessage(null, new FacesMessage("解析成功！"));
                    }
                }
            } catch (Exception e) {
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "解析文件错误！"));
                e.printStackTrace();
            } finally {
                if (file != null && file.exists()) {
                    file.delete();
                }
            }
        } else {
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "请上传文件！"));
            return;
        }
    }

    private boolean validate(FacesContext context, EntityAdvConfig ebp, boolean isAdd, List<EntityAdvConfig> ebpList) {
        if (Utils.isEmptyStr(ebp.getId())) {
            context.addMessage(null, new FacesMessage("生成时代码id不能为空！"));
            return false;
        }
        if (Utils.isEmptyStr(ebp.getAffiliation())) {
            context.addMessage(null, new FacesMessage("归属不能为空！"));
            return false;
        }
        if (Utils.isEmptyStr(ebp.getActName())) {
            context.addMessage(null, new FacesMessage("活动名称不能为空！"));
            return false;
        }
        if (Utils.isEmptyStr(ebp.getChannelName())) {
            context.addMessage(null, new FacesMessage("渠道名称不能为空！"));
            return false;
        }
        if (Utils.isEmptyStr(ebp.getAgent())) {
            context.addMessage(null, new FacesMessage("代理公司不能为空！"));
            return false;
        }
        if (Utils.isEmptyStr(ebp.getPlatform()) || "0".equals(ebp.getPlatform())) {
            context.addMessage(null, new FacesMessage("渠道平台不能为空！"));
            return false;
        }
        if (Utils.isEmptyStr(ebp.getPaytype())) {
            context.addMessage(null, new FacesMessage("结算方式不能为空！"));
            return false;
        }
        if (Utils.isEmptyStr(ebp.getAdvPosition())) {
            context.addMessage(null, new FacesMessage("广告位置不能为空！"));
            return false;
        }

        if (isAdd) {
            // 如果是添加，则ID不能重
            for (EntityAdvConfig e : ebpList) {
                if (ebp.getId().equals(e.getId())) {
                    context.addMessage(null, new FacesMessage("短链重复：id = " + ebp.getId()));
                    return false;
                }
            }
        }
        return true;
    }

    public EntityAdvConfig getEntity() {
        return entity;
    }

    public void setEntity(EntityAdvConfig entity) {
        this.entity = entity;
    }

    public List<EntityAdvConfig> getList() {
        return list;
    }

    public void setList(List<EntityAdvConfig> list) {
        this.list = list;
    }

    public int getUploadparamtype() {
        return uploadparamtype;
    }

    public void setUploadparamtype(int uploadparamtype) {
        this.uploadparamtype = uploadparamtype;
    }

    public static File getFile() {
        return file;
    }

    public static void setFile(File file) {
        AdvConfigAction.file = file;
    }

    public Map<String, Integer> getQueryGameParamTypeItmes() {
        return queryGameParamTypeItmes;
    }

    public void setQueryGameParamTypeItmes(Map<String, Integer> queryGameParamTypeItmes) {
        this.queryGameParamTypeItmes = queryGameParamTypeItmes;
    }
}
